package com.sinosoft.web.easyui.api;

import cn.com.sinux.spring.commons.PropertyCollection;
import cn.com.sinux.spring.exception.BusinessException;
import cn.com.sinux.spring.json.JsonFilter;
import cn.com.sinux.spring.utils.ConvertUtils;
import cn.com.sinux.spring.utils.PageUtils;
import com.sinosoft.hydra.um.LoginUser;
import com.sinosoft.hydra.um.condition.SearchBestProcessCondition;
import com.sinosoft.hydra.um.condition.SearchEBomCondition;
import com.sinosoft.hydra.um.condition.SearchProcessRecordCondition;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.model.LabChart;
import com.sinosoft.hydra.um.domain.permission.*;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.ProcessManageService;
import com.sinosoft.hydra.um.services.SysEBomService;
import com.sinosoft.hydra.um.services.SysLabService;
import com.sinosoft.hydra.um.services.SysParseService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/7/7.
 */
@Controller
@RequestMapping("api/lab")
public class SysLabApi {

    @Autowired
    private SysLabService sysLabService;
    @Autowired
    private ProcessManageService processManageService;
    @Autowired
    private SysEBomService sysEBomService;
    @Autowired
    private SysParseService sysParseService;

    /**
     * 实验首页面
     *
     * @return
     */
    @RequestMapping("index")
    @RequiresPermissions(value = "lab:data:index")
    public String index(Model model, @RequestParam(value = "eBomId", required = false) String eBomId) {
        model.addAttribute("groups", processManageService.findAllProcess());
        model.addAttribute("eBomId", eBomId);
        LoggerHelper.logInfo("访问了工艺参数记录首页面");
        return "hydra_easyui/lab/index";
    }

    /**
     * 实验记录页面
     *
     * @return
     */
    @RequestMapping("job")
    @RequiresPermissions(value = "lab:data:add")
    public String job(Model model,
                      @RequestParam(value = "processId", required = false) String processId,
                      @RequestParam(value = "eBomId", required = false) String eBomId) {
        TEBom teBom = sysEBomService.findOne(eBomId);
        TProcessTemplate processTemplate = processManageService.findOne(processId);
        model.addAttribute("ebom", teBom);
        model.addAttribute("processTemplate", processTemplate);
        Pageable pageable = PageUtils.buildPageRequest(1, 1);
        SearchProcessRecordCondition searchProcessRecordCondition = new SearchProcessRecordCondition();
        searchProcessRecordCondition.settProcessTemplate(processTemplate);
        Page<TProcessRecord> processRecords = sysLabService.findRecords(searchProcessRecordCondition, pageable);
        model.addAttribute("hasRecord", processRecords.getTotalElements() > 0);
        return "hydra_easyui/lab/job";
    }

    /**
     * @param loginUser
     * @param searchEBomCondition
     * @param processRecord
     * @return
     */
    @RequestMapping(value = "saveProcessData", method = RequestMethod.POST)
    @RequiresPermissions(value = "lab:data:add")
    @ResponseBody
    public Object saveProcessData(LoginUser loginUser,
                                  SearchEBomCondition searchEBomCondition, TProcessRecord processRecord) {
        TProcessRecord result = sysLabService.saveProcessData(loginUser, searchEBomCondition, processRecord);
        LoggerHelper.logInfo("对{}进行了{}工艺实验参数采集", new LoggerHelper.PropertyReader<TEBom>(result.getTeBoms(), "eName"),
                result.gettProcessTemplate().getProcessName());
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id"));
    }

    /**
     * 到ebom组装页面
     *
     * @param pageSize
     * @return
     */
    @RequestMapping("relative")
    @ResponseBody
    public Object relative(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
            @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize,
            SearchProcessRecordCondition searchProcessRecordCondition
    ) {
        Pageable pageable = PageUtils
                .buildPageRequest(pageNumber, pageSize, "id", "desc");
        Page<TProcessRecord> processRecords = sysLabService.findRecords(searchProcessRecordCondition, pageable);
        return JsonFilter.doPropertyFilter(processRecords, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id", "operateTime", "operator", "result"));
    }

    /**
     * 到ebom组装页面
     *
     * @param id
     * @return
     */
    @RequestMapping("getRecordInfo")
    @ResponseBody
    public Object getRecordInfo(@RequestParam(value = "id", required = true) String id) {
        TProcessRecord record = sysLabService.findOne(id);
        return JsonFilter.doPropertyFilter(record, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id", "result", "tProcessParameters"));
    }

    /**
     * 查看历史
     *
     * @param model
     * @param loginUser
     * @param id
     * @return
     */
    @RequestMapping("view")
    public String view(Model model,
                       LoginUser loginUser,
                       @RequestParam(value = "id", required = true) String id) {
        TProcessRecord record = sysLabService.findOne(id);
        model.addAttribute("record", record);
        return "hydra_easyui/lab/view";
    }

    /**
     * 到EBOM添加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("labRecords")
    @RequiresPermissions(value = "lab:data:history")
    public String labRecords(Model model, LoginUser loginUser,
                             @RequestParam(value = "id", required = true) String id) {
        TEBom teBom = sysEBomService.findOne(id);
        model.addAttribute("ebom", teBom);
        if (teBom != null) {
            List<TProcessRecord> records = teBom.gettProcessRecords();
            Collections.sort(records, new Comparator<TProcessRecord>() {

                public int compare(TProcessRecord processRecord, TProcessRecord processRecord2) {
                    return processRecord.getOperateTime().compareTo(processRecord2.getOperateTime());
                }
            });
            for(TProcessRecord record : records){
                record.setUpdatePermission(sysLabService.hasUpdatePermission(loginUser, record));
            }
            model.addAttribute("records", records);
        }
        //计算现有PBOM节点数
        return "hydra_easyui/lab/records";
    }

    /**
     * 到EBOM添加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("labHistory")
    @RequiresPermissions(value = "lab:data:history")
    public String toSearch(Model model,
                           @RequestParam(value = "id", required = false) String id) {
        TEBom teBom = sysEBomService.findOne(id);
        model.addAttribute("ebom", teBom);
        //计算现有PBOM节点数
        return "hydra_easyui/lab/history";
    }

    /**
     * 查询records的基本信息
     *
     * @param searchEBomCondition
     * @return
     */
    @RequestMapping("ebomRecords")
    @ResponseBody
    public Object ebomRecords(SearchEBomCondition searchEBomCondition) {
        List<TEBom> teBoms = sysEBomService.findEBoms(searchEBomCondition, null).getContent();
        return JsonFilter.doPropertyFilter(teBoms, new PropertyCollection()
                .addProperties(TEBom.class, "id", "eName", "code", "tProcessRecords")
                .addProperties(TProcessRecord.class, "id", "tProcessTemplate")
                .addProperties(TProcessTemplate.class, "processName", "processCover"));
    }

    /**
     * 查询records的基本信息
     *
     * @param id
     * @return
     */
    @RequestMapping("record")
    @ResponseBody
    public Object record(@RequestParam(value = "id", required = false) String id) {
        TProcessRecord record = sysLabService.findOne(id);
        return JsonFilter.doPropertyFilter(record, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id", "tProcessTemplate", "operator", "result", "tProcessParameters")
                .addProperties(TProcessTemplate.class, "processName", "processCover", "tProcessAttributes")
                .addProperties(TProcessAttribute.class, "fieldName", "fieldType", "fieldTypeParam", "remark", "notNull", "useDevice", "orderNo")
                .addProperties(TProcessParameter.class, "fieldName", "fieldType", "parameterValue", "unit", "parameterDevice"));
    }

    /**
     * 查询records的基本信息
     *
     * @param searchProcessRecordCondition
     * @return
     */
    @RequestMapping("ebomRecordDetails")
    @ResponseBody
    public Object ebomRecordDetails(SearchProcessRecordCondition searchProcessRecordCondition) {
        List<TProcessRecord> teBoms = sysLabService.findRecords(searchProcessRecordCondition, null).getContent();
        return JsonFilter.doPropertyFilter(teBoms, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id", "tProcessTemplate", "operator", "result", "tProcessParameters")
                .addProperties(TProcessAttribute.class, "fieldName", "fieldType", "fieldTypeParam", "remark", "notNull")
                .addProperties(TProcessTemplate.class, "processName", "processCover", "tProcessAttributes", "useDevice", "orderNo")
                .addProperties(TProcessParameter.class, "fieldName", "fieldType", "parameterValue", "unit", "parameterDevice"));
    }

    /**
     * 修改记录
     *
     * @param loginUser
     * @param record
     * @return
     */
    @RequestMapping(value = "modifyRecord", method = RequestMethod.POST)
    @ResponseBody
    public Object record(LoginUser loginUser, TProcessRecord record) {
        TProcessRecord result = sysLabService.modifyRecord(loginUser, record);
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(TProcessRecord.class, "id", "tProcessTemplate", "operator", "result", "tProcessParameters")
                .addProperties(TProcessTemplate.class, "processName", "processCover")
                .addProperties(TProcessParameter.class, "fieldName", "fieldType", "parameterValue", "unit", "parameterDevice"));
    }



    /**
     * 统计已完成的实验数
     *
     * @return
     */
    @RequestMapping("recordCount")
    @ResponseBody
    public Object recordCount(HttpServletResponse response) {
        SearchProcessRecordCondition searchProcessRecordCondition = new SearchProcessRecordCondition();
        searchProcessRecordCondition.setType(BaseConstant.RecordType.RECORD_TYPE_NORMAL.name());
        List<TProcessRecord> records = sysLabService.findRecords(searchProcessRecordCondition, null).getContent();
        return new LabChart(records);
    }

    /**
     * 实验数据转换
     *
     * @param code      设备编码
     * @param start     开始时间
     * @param end       结束时间
     * @param filePath  文件路径，逗号分隔
     * @param loginUser 当前登录用户
     * @return
     */
    @RequestMapping(value = "parse", method = RequestMethod.POST)
    @ResponseBody
    public Object parse(
            @RequestParam(value = "random", required = true) String random,
            @RequestParam(value = "code", required = true) String code,
            @RequestParam(value = "startTime", required = false) Date start,
            @RequestParam(value = "endTime", required = false) Date end,
            @RequestParam(value = "filePath", required = true) String filePath,
            LoginUser loginUser) {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(filePath)) {
            throw new BusinessException("实验参数未填写正确，请重新填写！");
        }
        TExperimentalData experimentalData = sysParseService.doParser(random, code, start, end, ConvertUtils.loadStringList(filePath, ","), loginUser);
        return JsonFilter.doPropertyFilter(experimentalData, new PropertyCollection()
                .addProperties(TExperimentalData.class, "id", "experimentalDataPath", "status", "failureMsg", "hasChart"));
    }
}
